"""
仪表盘视图
"""
from datetime import datetime, timedelta
from django.db.models import Count, Q
from django.utils import timezone
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from students.models import Student
from resume_management.models import Resume
from interviews.models import Interview
from jobs.models import Job, JobApplication, Company
from accounts.models import User
from .serializers import (
    DashboardStatsSerializer,
    StudentEmploymentStatsSerializer,
    ResumeStatsSerializer,
    InterviewStatsSerializer,
    JobStatsSerializer,
    MonthlyTrendSerializer,
    UserRoleStatsSerializer,
    RecentActivitySerializer,
    PersonalizedStatsSerializer,
    SystemOverviewSerializer,
    UserActivitySerializer,
    GrowthTrendSerializer
)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def overview_stats(request):
    """获取仪表盘概览统计数据"""
    try:
        # 统计各种数据总数
        total_students = Student.objects.count()
        total_resumes = Resume.objects.count()
        total_interviews = Interview.objects.count()
        total_jobs = Job.objects.count()
        
        # 统计公司数量（从岗位中去重）
        total_companies = Job.objects.values('company__name').distinct().count()
        
        # 统计申请总数
        total_applications = JobApplication.objects.count()
        
        data = {
            'total_students': total_students,
            'total_resumes': total_resumes,
            'total_interviews': total_interviews,
            'total_jobs': total_jobs,
            'total_companies': total_companies,
            'total_applications': total_applications
        }
        
        serializer = DashboardStatsSerializer(data)
        return Response(serializer.data)
        
    except Exception as e:
        return Response(
            {'error': f'获取概览统计失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def student_employment_stats(request):
    """获取学生就业状态统计"""
    try:
        # 统计各种就业状态的学生数量
        employment_stats = Student.objects.aggregate(
            employed=Count('id', filter=Q(employment_status='employed')),
            unemployed=Count('id', filter=Q(employment_status='unemployed')),
            further_study=Count('id', filter=Q(employment_status='further_study')),
            self_employed=Count('id', filter=Q(employment_status='self_employed')),
            military=Count('id', filter=Q(employment_status='military'))
        )
        
        # 处理None值
        for key in employment_stats:
            if employment_stats[key] is None:
                employment_stats[key] = 0
        
        serializer = StudentEmploymentStatsSerializer(employment_stats)
        return Response(serializer.data)
        
    except Exception as e:
        return Response(
            {'error': f'获取就业统计失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def resume_stats(request):
    """获取简历状态统计"""
    try:
        # 统计各种简历状态的数量
        resume_stats = Resume.objects.aggregate(
            draft=Count('id', filter=Q(status='draft')),
            in_progress=Count('id', filter=Q(status='in_progress')),
            pending_review=Count('id', filter=Q(status='pending_review')),
            under_review=Count('id', filter=Q(status='under_review')),
            approved=Count('id', filter=Q(status='approved')),
            rejected=Count('id', filter=Q(status='rejected')),
            needs_revision=Count('id', filter=Q(status='needs_revision'))
        )
        
        # 处理None值
        for key in resume_stats:
            if resume_stats[key] is None:
                resume_stats[key] = 0
        
        serializer = ResumeStatsSerializer(resume_stats)
        return Response(serializer.data)
        
    except Exception as e:
        return Response(
            {'error': f'获取简历统计失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def interview_stats(request):
    """获取面试状态统计"""
    try:
        # 统计各种面试状态的数量
        interview_stats = Interview.objects.aggregate(
            scheduled=Count('id', filter=Q(status='scheduled')),
            in_progress=Count('id', filter=Q(status='in_progress')),
            completed=Count('id', filter=Q(status='completed')),
            cancelled=Count('id', filter=Q(status='cancelled'))
        )
        
        # 处理None值
        for key in interview_stats:
            if interview_stats[key] is None:
                interview_stats[key] = 0
        
        serializer = InterviewStatsSerializer(interview_stats)
        return Response(serializer.data)
        
    except Exception as e:
        return Response(
            {'error': f'获取面试统计失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def job_stats(request):
    """获取岗位状态统计"""
    try:
        # 统计各种岗位状态的数量
        job_stats = Job.objects.aggregate(
            published=Count('id', filter=Q(status='published')),
            draft=Count('id', filter=Q(status='draft')),
            closed=Count('id', filter=Q(status='closed')),
            expired=Count('id', filter=Q(status='expired'))
        )
        
        # 统计申请状态
        application_stats = JobApplication.objects.aggregate(
            pending=Count('id', filter=Q(status='pending')),
            approved=Count('id', filter=Q(status='approved')),
            rejected=Count('id', filter=Q(status='rejected')),
            total=Count('id')
        )
        
        # 处理None值
        for key in job_stats:
            if job_stats[key] is None:
                job_stats[key] = 0
                
        for key in application_stats:
            if application_stats[key] is None:
                application_stats[key] = 0
        
        job_stats['applications'] = application_stats
        
        serializer = JobStatsSerializer(job_stats)
        return Response(serializer.data)
        
    except Exception as e:
        return Response(
            {'error': f'获取岗位统计失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def monthly_trends(request):
    """获取月度趋势数据"""
    try:
        months = int(request.GET.get('months', 6))
        
        # 计算日期范围
        end_date = timezone.now().date()
        start_date = end_date - timedelta(days=months * 30)
        
        trends = []
        
        # 生成每个月的数据
        for i in range(months):
            month_start = start_date + timedelta(days=i * 30)
            month_end = month_start + timedelta(days=30)
            
            # 统计该月的面试数据
            interviews_count = Interview.objects.filter(
                created_at__date__gte=month_start,
                created_at__date__lt=month_end
            ).count()

            completed_interviews_count = Interview.objects.filter(
                created_at__date__gte=month_start,
                created_at__date__lt=month_end,
                status='completed'
            ).count()

            # 统计该月的申请数据
            applications_count = JobApplication.objects.filter(
                applied_at__date__gte=month_start,
                applied_at__date__lt=month_end
            ).count()

            approved_applications_count = JobApplication.objects.filter(
                applied_at__date__gte=month_start,
                applied_at__date__lt=month_end,
                status='approved'
            ).count()
            
            trends.append({
                'month': f'{month_start.month}月',
                'interviews': interviews_count,
                'completed_interviews': completed_interviews_count,
                'applications': applications_count,
                'approved_applications': approved_applications_count
            })
        
        serializer = MonthlyTrendSerializer(trends, many=True)
        return Response(serializer.data)
        
    except Exception as e:
        return Response(
            {'error': f'获取月度趋势失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def user_role_stats(request):
    """获取用户角色统计"""
    try:
        # 统计各种角色的用户数量
        role_stats = User.objects.aggregate(
            admin=Count('id', filter=Q(role='admin')),
            teacher=Count('id', filter=Q(role='teacher')),
            student=Count('id', filter=Q(role='student')),
            total=Count('id')
        )
        
        # 处理None值
        for key in role_stats:
            if role_stats[key] is None:
                role_stats[key] = 0
        
        serializer = UserRoleStatsSerializer(role_stats)
        return Response(serializer.data)
        
    except Exception as e:
        return Response(
            {'error': f'获取用户角色统计失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def recent_activities(request):
    """获取最近活动"""
    try:
        limit = int(request.GET.get('limit', 10))
        
        activities = []
        
        # 获取最近的简历提交
        recent_resumes = Resume.objects.filter(
            status='pending_review'
        ).order_by('-updated_at')[:limit//2]
        
        for resume in recent_resumes:
            activities.append({
                'id': resume.id,
                'type': 'resume_submit',
                'title': '简历提交审核',
                'description': f'{resume.student.name} 提交了简历 "{resume.title}"',
                'user': resume.student.name,
                'created_at': resume.updated_at
            })
        
        # 获取最近的面试安排
        recent_interviews = Interview.objects.order_by('-created_at')[:limit//2]

        for interview in recent_interviews:
            activities.append({
                'id': interview.id,
                'type': 'interview_schedule',
                'title': '面试安排',
                'description': f'安排了与 {interview.student.name} 的面试: {interview.title}',
                'user': interview.student.name,
                'created_at': interview.created_at
            })
        
        # 按时间排序
        activities.sort(key=lambda x: x['created_at'], reverse=True)
        activities = activities[:limit]
        
        serializer = RecentActivitySerializer(activities, many=True)
        return Response(serializer.data)
        
    except Exception as e:
        return Response(
            {'error': f'获取最近活动失败: {str(e)}'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def personalized_stats(request):
    """获取个性化统计数据"""
    try:
        user = request.user
        role = user.role

        if role == 'admin':
            # 管理员统计
            data = {
                'total_users': User.objects.count(),
                'active_users': User.objects.filter(is_active=True).count(),
                'pending_reviews': Resume.objects.filter(status='pending_review').count(),
                'system_health': 'good'
            }
        elif role == 'teacher':
            # 教师统计
            # 获取该教师负责的学生
            my_students = Student.objects.filter(advisor=user)

            data = {
                'my_students_count': my_students.count(),
                'pending_resumes': Resume.objects.filter(
                    student__in=my_students,
                    status='pending_review'
                ).count(),
                'monthly_interviews': Interview.objects.filter(
                    student__in=my_students,
                    created_at__month=timezone.now().month
                ).count(),
                'employment_rate': calculate_employment_rate(my_students)
            }
        else:
            # 学生统计
            try:
                student = Student.objects.get(user=user)
                data = {
                    'resume_count': Resume.objects.filter(student=student).count(),
                    'interview_count': Interview.objects.filter(student=student).count(),
                    'application_count': JobApplication.objects.filter(student=student).count(),
                    'resume_completion': get_resume_completion(student)
                }
            except Student.DoesNotExist:
                data = {
                    'resume_count': 0,
                    'interview_count': 0,
                    'application_count': 0,
                    'resume_completion': 0
                }

        result = {
            'role': role,
            'data': data
        }

        serializer = PersonalizedStatsSerializer(result)
        return Response(serializer.data)

    except Exception as e:
        return Response(
            {'error': f'获取个性化统计失败: {str(e)}'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def system_overview(request):
    """获取系统概览（管理员专用）"""
    try:
        if request.user.role != 'admin':
            return Response(
                {'error': '权限不足'},
                status=status.HTTP_403_FORBIDDEN
            )

        # 计算系统运行时间（模拟）
        from datetime import datetime
        start_time = timezone.make_aware(datetime(2024, 1, 1))
        uptime_days = (timezone.now() - start_time).days

        data = {
            'total_users': User.objects.count(),
            'active_users': User.objects.filter(
                last_login__gte=timezone.now() - timedelta(days=30)
            ).count(),
            'total_data_size': '2.5 GB',  # 模拟数据
            'system_uptime': f'{uptime_days} 天'
        }

        serializer = SystemOverviewSerializer(data)
        return Response(serializer.data)

    except Exception as e:
        return Response(
            {'error': f'获取系统概览失败: {str(e)}'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def user_activity(request):
    """获取用户活跃度统计"""
    try:
        if request.user.role != 'admin':
            return Response(
                {'error': '权限不足'},
                status=status.HTTP_403_FORBIDDEN
            )

        period = request.GET.get('period', 'week')

        if period == 'day':
            days = 7
        elif period == 'week':
            days = 30
        else:  # month
            days = 90

        activities = []
        end_date = timezone.now().date()

        for i in range(days):
            date = end_date - timedelta(days=i)

            # 统计当天活跃用户（有登录记录）
            active_users = User.objects.filter(
                last_login__date=date
            ).count()

            # 统计当天新注册用户
            new_users = User.objects.filter(
                date_joined__date=date
            ).count()

            activities.append({
                'date': date,
                'active_users': active_users,
                'new_users': new_users,
                'login_count': active_users  # 简化处理
            })

        activities.reverse()  # 按时间正序

        serializer = UserActivitySerializer(activities, many=True)
        return Response(serializer.data)

    except Exception as e:
        return Response(
            {'error': f'获取用户活跃度失败: {str(e)}'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def growth_trends(request):
    """获取数据增长趋势"""
    try:
        if request.user.role != 'admin':
            return Response(
                {'error': '权限不足'},
                status=status.HTTP_403_FORBIDDEN
            )

        period = request.GET.get('period', 'month')

        if period == 'week':
            days = 7
        elif period == 'month':
            days = 30
        else:  # quarter
            days = 90

        # 计算增长率
        end_date = timezone.now()
        start_date = end_date - timedelta(days=days)
        previous_start = start_date - timedelta(days=days)

        # 当前周期数据
        current_students = Student.objects.filter(
            created_at__gte=start_date
        ).count()
        current_resumes = Resume.objects.filter(
            created_at__gte=start_date
        ).count()
        current_interviews = Interview.objects.filter(
            created_at__gte=start_date
        ).count()
        current_jobs = Job.objects.filter(
            created_at__gte=start_date
        ).count()

        # 上一周期数据
        previous_students = Student.objects.filter(
            created_at__gte=previous_start,
            created_at__lt=start_date
        ).count()
        previous_resumes = Resume.objects.filter(
            created_at__gte=previous_start,
            created_at__lt=start_date
        ).count()
        previous_interviews = Interview.objects.filter(
            created_at__gte=previous_start,
            created_at__lt=start_date
        ).count()
        previous_jobs = Job.objects.filter(
            created_at__gte=previous_start,
            created_at__lt=start_date
        ).count()

        # 计算增长率
        def calculate_growth(current, previous):
            if previous == 0:
                return 100.0 if current > 0 else 0.0
            return ((current - previous) / previous) * 100

        data = {
            'period': period,
            'students_growth': calculate_growth(current_students, previous_students),
            'resumes_growth': calculate_growth(current_resumes, previous_resumes),
            'interviews_growth': calculate_growth(current_interviews, previous_interviews),
            'jobs_growth': calculate_growth(current_jobs, previous_jobs)
        }

        serializer = GrowthTrendSerializer(data)
        return Response(serializer.data)

    except Exception as e:
        return Response(
            {'error': f'获取增长趋势失败: {str(e)}'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


# 辅助函数
def calculate_employment_rate(students):
    """计算就业率"""
    if not students.exists():
        return 0.0

    employed_count = students.filter(
        employment_status__in=['employed', 'self_employed']
    ).count()

    return round((employed_count / students.count()) * 100, 2)


def get_resume_completion(student):
    """获取学生简历完成度"""
    try:
        resume = Resume.objects.filter(student=student).first()
        if resume:
            return float(resume.completion_rate)
        return 0.0
    except:
        return 0.0
